layui.define('layer', function(exports){
	var $ = layui.$,layer = layui.layer;
	$.getScript(layui.cache.base+"/ctyun/plupload.full.min.js");
	exports('ctyun', {
        loader:function (options,callback) {
			console.log(options);
            $.getScript(layui.cache.base+"/ctyun/oos-sdk-6.0.min.js",function () {
				if(!options.endPoint){
                    layer.msg('初始化参数：endPoint不能为空.', {icon: 2});
                    return;
                }
				if(!options.accessKeyId){
                    layer.msg('初始化参数：accessKeyId不能为空.', {icon: 2});
                    return;
                }
				if(!options.secretAccessKey){
                    layer.msg('初始化参数：secretAccessKey不能为空.', {icon: 2});
                    return;
                }
				if(!options.BucketName){
                    layer.msg('初始化参数：BucketName不能为空.', {icon: 2});
                    return;
                }
				
				var client = new OOS.S3({
					accessKeyId: options.accessKeyId,
					secretAccessKey: options.secretAccessKey,
					endpoint: options.endPoint,
					signatureVersion: 'v4', // 可选v2 或v4
					apiVersion: '2006-03-01',
					s3ForcePathStyle: true
				});
				var initialId = "";
				var tempMulti = [];
				var MultipartUpload = {
					Parts: []
				};
				
				var upload = new plupload.Uploader({
                    runtimes: 'html5,flash,silverlight,html4',//设置运行环境，会按设置的顺序，可以选择的值有html5,gears,flash,silverlight,browserplus,html
                    flash_swf_url: layui.cache.base+'dream/plupload/Moxie.swf',
                    silverlight_xap_url: layui.cache.base+'dream/plupload/Moxie.xap',
                    url: options.endPoint,//上传文件路径
                    max_file_size: options.max_file_size||'1tb',//100b, 10kb, 10mb, 1gb, 1tb
                    chunk_size: options.chunk_size||'5mb',//分块大小，小于这个大小的不分块
                    unique_names: options.unique_names || true,//生成唯一文件名
                    browse_button: options.browse_button||'plupload',
                    multi_selection: options.multi_selection || true,//是否可以选择多个，true为可以
                    filters: options.filters || [],
                    init: {
                        FilesAdded: function (uploader, files) {
                            if(typeof options.FilesAdded === 'function'){
                                options.FilesAdded(uploader,files);
                            }else{
								layer.load();
								//初始化天翼云分片上传
								client.createMultipartUpload({Bucket: options.BucketName,Key: files[0].name}, function (err, data) {
									if (err) console.log(err, err.stack); // an error occurredw
									else     console.log(data);           // successful response
									initialId = data.UploadId;
									uploader.start();
								});
                            }
                            return false;
                        },
                        FileUploaded: function (uploader, file, info) {
                            //文件上传完毕触发
							// console.log("+++++上传完毕+++++++");
                            if(typeof options.FileUploaded === 'function'){
                                options.FileUploaded(uploader,file,info);
                            }
                        },
                        ChunkUploaded: function (uploader, file, info) {
                            //文件上传完毕触发
							// console.log("+++++分片上传完毕+++++++");
                            if(typeof options.FileUploaded === 'function'){
                                options.FileUploaded(uploader,file,info);
                            }
                        },
						BeforeChunkUpload(uploader, file, args, chunkBlob, current) {
							var params = {
								Body: chunkBlob.getSource(),
								Bucket: options.BucketName,
								Key: file.name,
								PartNumber: args.chunk+1,
								UploadId: initialId
							};
							client.uploadPart(params, function (err, data) {
								if (err) console.log(err, err.stack); // an error occurred
								else {
									// MultipartUpload必须排序故放到缓存数组中
									// MultipartUpload.Parts.push({PartNumber: args.chunk+1, ETag: data.ETag.replace(/\"/g, "")})
									tempMulti[args.chunk] = data.ETag.replace(/\"/g, "");
									if(args.chunk+1 == args.chunks){
										for(let index in tempMulti) {
											console.log(index,tempMulti[index]);
											MultipartUpload.Parts.push({PartNumber: Number(index)+1, ETag: tempMulti[index]})
										};																	
										var params = {
											Bucket: options.BucketName,
											Key: file.name,
											UploadId: initialId,
											MultipartUpload: MultipartUpload
										};
										client.completeMultipartUpload(params, function (err, data) {
											if (err) console.log(err, err.stack); // an error occurred
											else     console.log(data);           // successful response
											if(typeof options.UploadComplete === 'function'){
												options.UploadComplete(data);
											}
										});
									}
								}
							});
						},
						BeforeUpload: function(uploader, file) {
							layer.closeAll('loading');
							if(typeof options.BeforeUpload === 'function'){
                                options.BeforeUpload(uploader,file);
                            }
						},
                        UploadComplete: function (uploader, files) {
							
							/*//异步原因移动到合并分片文件后
							if(typeof options.UploadComplete === 'function'){
								options.UploadComplete(files);
							}*/
                        },
                        UploadProgress: function (uploader, file) {
                            console.log("上传进度为：" + file.percent + "%");
                            if(typeof options.UploadProgress === 'function'){
                                options.UploadProgress(file);
                            }
                        },
                        //当发生错误时触发监听函数
                        Error: function (up, err) {
                            if(typeof options.Error === 'function'){
                                options.Error(up,err);
                            }else if (err.code == -600) {
                                layer.open({
                                    title: '上传错误'
                                    ,content: '选择的文件太大了，最大不能超过'+(options.max_file_size||'1tb'),
                                    icon:2
                                });
                            }
                            else if (err.code == -601) {
                                layer.open({
                                    title: '上传错误'
                                    ,content: '选择的文件后缀不对',
                                    icon:2
                                });
                            }
                            else if (err.code == -602) {
                                layer.open({
                                    title: '上传错误'
                                    ,content: '请勿重复上传同一个文件',
                                    icon:2
                                });
                            }
                            else {
                                alert("\nError xml:" + err.response, "");
                            }
                        }
                    }
                });
                if(options.container){
                    upload.setOption("container", options.container); //按钮容器，可以为ID或者DOM(document.getElementById)
                }
                if(options.drop_element){
                    upload.setOption("drop_element", options.drop_element); //拖拽容器，可以为ID或者DOM(document.getElementById)
                }
                if(typeof callback === 'function'){
                    callback(upload)
                }else{
                    upload.init();
                }
            });
        }
	})
});